/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package simple;

import algorithm.Environment;
import algorithm.Individual;
import java.util.Comparator;

/** A comparator for Individuals based on fitness
 *
 * @author vermaak
 */
public class IndividualComparator implements Comparator<Individual> {

    private Environment environment;

    public IndividualComparator(Environment environment) {
        this.environment = environment;
    }

    // Return the individual with the highest fitness first.
    public int compare(Individual o1, Individual o2) {
        double fitness1 = Double.NaN;
        double fitness2 = Double.NaN;
        try {
            fitness1 = o1.getFitness(environment);
            fitness2 = o2.getFitness(environment);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (Double.isNaN(fitness2) || Double.isNaN(fitness1)) {
            throw new RuntimeException("Fitness not set.");
        }
        return -Double.compare(fitness1, fitness2);
    }
}
